// TCP 套接字编程（socket）
// HTTP 请求和响应格式

// 实现HTTP服务器，通过浏览器向服务器发送请求，服务器组织响应，显示Hello World页面以及请求信息；

// 基于 TCP 的服务器，它监听某个端口（如 8080），当浏览器访问 http://localhost:808 时，服务器收到请求后，返回一个包含 “Hello World” 和请求路径的 HTML 页面。
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

// void handle_client(int client_fd) {
//     // 读取请求
//     char buffer[1024];
//     int bytes_read = read(client_fd, buffer, 1024);
//     if (bytes_read < 0) {
//         perror("read failed");
//         exit(EXIT_FAILURE);
//     }
//     std::cout << "Received request: " << buffer << std::endl;

//     // 组织响应
//     std::string response = "HTTP/1.1 200 OK\r\n";
//     response += "Content-Type: text/html\r\n";
//     response += "\r\n";
//     response += "<html><body><h1>Hello World!</h1><p>Request path: ";
//     response += buffer;
//     response += "</p></body></html>";

//     // 发送响应 
//     send(client_fd, response.c_str(), response.size(), 0);
//     close(client_fd);
// }
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

void handle_client(int client_fd) {
    char buffer[4096];
    int bytes_read = recv(client_fd, buffer, sizeof(buffer) - 1, 0);
    if (bytes_read <= 0) {
        if (bytes_read == 0) {
            std::cerr << "Client disconnected unexpectedly.\n";
        } else {
            perror("recv failed");
        }
        close(client_fd);
        return;
    }

    buffer[bytes_read] = '\0'; // 确保字符串结尾
    std::cout << "=== Received Request ===\n" << buffer << std::endl;

    // 提取请求路径
    std::string request(buffer);
    size_t first_space = request.find(' ');
    size_t second_space = request.find(' ', first_space + 1);
    std::string path = "/";
    if (first_space != std::string::npos && second_space != std::string::npos) {
        path = request.substr(first_space + 1, second_space - first_space - 1);
    }

    // 构造响应
    std::string response =
        "HTTP/1.1 200 OK\r\n"
        "Content-Type: text/html\r\n"
        "Connection: close\r\n"
        "\r\n"
        "<html><body>"
        "<h1>Hello World</h1>"
        "<p>You requested path: " + path + "</p>"
        "</body></html>";

    send(client_fd, response.c_str(), response.size(), 0);
    close(client_fd);
}
int main() {

    int server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd < 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    struct sockaddr_in address;
    memset(&address, 0, sizeof(address));  //每个字节都用0填充
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(8081); // 使用 8081 端口

    // 绑定地址和端口
    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
        perror("bind failed");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    // 开始监听
    if (listen(server_fd, 3) < 0) {
        perror("listen failed");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    std::cout << "HTTP server is running on port 8081...\n";
    
    //接收客户端请求
    while (true) {
        struct sockaddr_in client_addr;
        socklen_t client_len = sizeof(client_addr);

        int client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_len);
        if (client_fd < 0) {
            perror("accept failed");
            continue;
        }
        std::cout << "New connection accepted." << std::endl;
        // 处理客户端请求
        handle_client(client_fd);
    }
    // 关闭服务器套接字
    close(server_fd);
    std::cout << "Server shutting down." << std::endl;
    
    return 0;
}

// int main() {
//     // 创建 socket
//     int server_fd = socket(AF_INET, SOCK_STREAM, 0);
//     if(server_fd<0)
//     {
//         perror("socket failed");
//         exit(EXIT_FAILURE);
//     }
//     struct sockaddr_in address;
//     address.sin_family = AF_INET;
//     address.sin_addr.s_addr = INADDR_ANY;
//     address.sin_port = htons(8081); // 监听端口 8080
//     // 绑定地址和端口
//     bind(server_fd, (struct sockaddr *)&address, sizeof(address));

//     // 开始监听
//     listen(server_fd, 3);

//     while (true) {
//         // 接收客户端连接
//         int client_fd = accept(server_fd, NULL, NULL);
//         std::cout<< "New connection accepted." << std::endl;
//         // 处理客户端请求
//         handle_client(client_fd);
//     }

//     return 0;
// }